<template>
  <div class="myDialog">
    <!-- 弹窗组件 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="title"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      width="50%">
      <el-form
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :disabled="isDisabled"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="$t('menuType')" prop="type">
          <el-radio-group v-model="form.type" size="mini" style="width: 320px">
            <el-radio-button :label="0">{{ $t('system') }}</el-radio-button>
            <el-radio-button :label="1">{{ $t('catalog') }}</el-radio-button>
            <el-radio-button :label="2">{{ $t('menu') }}</el-radio-button>
            <el-radio-button :label="3">{{ $t('button') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('menuCategory')" prop="category">
          <el-radio-group v-model="form.category" size="mini" style="width: 220px">
            <el-radio-button :label="1">{{ $t('webpage') }}</el-radio-button>
            <el-radio-button :label="2">{{ $t('apppage') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="form.type != '3'" :label="$t('icon')" prop="icon">
          <el-popover
            placement="bottom-start"
            width="450"
            trigger="click"
            @show="$refs['iconSelect'].reset()"
          >
            <IconSelect ref="iconSelect" @selected="selected" />
            <el-input slot="reference" v-model="form.icon" :placeholder="$t('selectIcon')" style="width: 178px;" readonly>
              <svg-icon v-if="form.icon" slot="prefix" :icon-class="form.icon" class="el-input__icon" style="height: 32px;width: 16px;" />
              <i v-else slot="prefix" class="el-icon-search el-input__icon" />
            </el-input>
          </el-popover>
        </el-form-item>
        <el-form-item v-show="form.type != '3'" :label="$t('visible')" prop="visible">
          <el-radio-group v-model="form.visible" size="mini">
            <el-radio-button :label="1">{{ $t('visibled') }}</el-radio-button>
            <el-radio-button :label="0">{{ $t('disvisible') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="form.type != '3'" :label="$t('superAdminFunction')" prop="is_SuperAdmin">
          <el-radio-group v-model="form.is_SuperAdmin" size="mini">
            <el-radio-button :label="1">{{ $t('yes') }}</el-radio-button>
            <el-radio-button :label="0">{{ $t('no') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="form.type == '2'" :label="$t('cache')" prop="cache">
          <el-radio-group v-model="form.cache" size="mini">
            <el-radio-button :label="1">{{ $t('yes') }}</el-radio-button>
            <el-radio-button :label="0">{{ $t('no') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="form.type != '3'" :label="$t('link')" prop="link">
          <el-radio-group v-model="form.link" size="mini">
            <el-radio-button :label="1">{{ $t('yes') }}</el-radio-button>
            <el-radio-button :label="0">{{ $t('no') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('menuDescription')" prop="description">
          <el-input v-model="form.description" :placeholder="$t('menuDescription')" style="width: 178px" />
        </el-form-item>
        <el-form-item :label="$t('menuName')" prop="name">
          <el-input v-model="form.name" :placeholder="$t('menuName')" style="width: 178px" />
        </el-form-item>
        <el-form-item :label="$t('order')" prop="order">
          <el-input-number v-model.number="form.order" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item v-show="form.type != '3'" :label="$t('resourceName')" prop="resourceName">
          <el-input v-model="form.resourceName" style="width: 178px;" />
        </el-form-item>
        <el-form-item v-show="form.type == '3'" :label="$t('powerSign')" prop="power">
          <el-input v-model="form.power" style="width: 178px;" />
        </el-form-item>
        <el-row>
          <el-form-item v-show="form.type != '3'" :label="$t('routeUrl')" prop="formName">
            <el-input v-model="form.formName" style="width: 350px;" placeholder="" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item v-show="form.type != '3' || form.id == null" :label="$t('parentMenu')" prop="parentId">
            <treeselect
              v-model="form.parentId"
              :options="menus"
              :load-options="loadMenus"
              :placeholder="$t('parentMenu')"
              :no-children-text="$t('noMoreData')"
              style="width: 350px;"
            />
          </el-form-item>
        </el-row>
        <el-form-item v-show="form.type == '0'" :label="$t('isShowHome')" prop="isShow">
          <el-radio-group v-model="form.isShow" size="mini">
            <el-radio-button :label="1">{{ $t('yes') }}</el-radio-button>
            <el-radio-button :label="0">{{ $t('no') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="form.type == '0'" :label="$t('formName')" prop="remark">
          <el-input v-model="form.remark" style="width: 178px;" placeholder="" />
        </el-form-item>
        <el-row>
          <el-form-item v-show="form.type == '0'" :label="$t('formdetail')" prop="formDescription">
            <el-input
              :rows="2"
              v-model="form.formDescription"
              type="textarea"
              style="width: 500px;" />
          </el-form-item>
        </el-row>
        <!-- <el-form-item v-show="form.type == '0'" :label="$t('bgImage')" prop="bgImage">
          <template
            v-if="imageUrl || form.bgImagePath"
            style="display: inline-block"
          >
            <el-button
              type="danger"
              style="opacity: 0.6"
              icon="el-icon-delete"
              circle
              @click="ImgRemove"
            />
          </template>
          <el-upload
            ref="upload"
            :headers="headers"
            :action="updateAvatarApi"
            :show-file-list="false"
            :auto-upload="true"
            :on-success="uploadSuccess"
            :on-change="beforeUpload"
            class="upload-add"
            style="display: inline-block"
            name="uploadFile"
            accept=".PNG,.JPG,.GIF"
          >
            <template v-if="imageUrl || form.bgImagePath">
              <img
                :src="
                  form.bgImagePath
                    ? imgUrlFormatter(form.bgImagePath)
                    : imageUrl
                "
                style="width: 100px; height: 70px; margin-left: 0px"
              >
            </template>
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
              style="margin-left: 50px"
            />
          </el-upload>
        </el-form-item> -->
      </el-form>
      <div v-if="!isDisabled" slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-close" @click="closeDialog">{{
          $t("cancel")
        }}</el-button>
        <el-button v-btnThrottle="doSave" type="primary" icon="el-icon-receiving">{{ $t('save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import crudMenu from '@/api/system/menu'
import IconSelect from '@/components/IconSelect'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import crudJob from '@/api/system/menu'
import mySetting from '@/mixins/mySetting'
import { getToken } from '@/utils/auth'
export default {
  name: 'MyDialog',
  components: { Treeselect, IconSelect },
  mixins: [mySetting],
  props: {
    form: {
      type: Object,
      default: () => ({})
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      headers: {
        Token: getToken()
      },
      dialogFormVisible: false,
      show: true,
      menus: [],
      imageUrl: '',
      fileTypeList: ['JPG', 'PNG', 'JPEG', 'GIF'], // 允许的文件上传类型,与之比较时全部转大写进行比较
      rules: {
        description: [
          { required: true, message: this.$t('menuDescriptionRequired'), trigger: 'blur' }
        ],
        type: [
          { required: true, message: this.$t('menuTypeRequired'), trigger: 'change' }
        ],
        category: [
          { required: true, message: this.$t('menuCategoryRequired'), trigger: 'change' }
        ],
        name: [
          { required: true, message: this.$t('menuNameRequired'), trigger: 'blur' }
        ]
      } // 表单校验规则
    }
  },
  computed: {
    ...mapGetters(['updateAvatarApi', 'baseApi'])
  },
  methods: {
    // 新增数据
    doSave() {
      this.$refs['ruleForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.form.id) {
          // 存在id则是更新
          crudJob.edit({ id: this.form.id, ...this.form }).then(res => {
            this.doMerge(res)
          })
        } else {
          // 不存在id则是新增
          crudJob.add(this.form).then(res => {
            this.doMerge(res)
          })
        }
        this.imageUrl = ''
      })
    },
    // 打开弹窗
    openDialog(val, id) {
      this.form.order = 0
      this.menus = []
      if (val === 2) {
        if (id != null) {
          if (this.form.parentId === null) {
            this.form.parentId = 0
          }
          this.getSupDepts(id)
        } else {
          this.menus.push({ id: 0, label: this.$t('topmenu'), children: null })
        }
      } else {
        this.menus.push({ id: 0, label: this.$t('topmenu'), children: null })
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate()
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.$emit('closeDialog')
      this.dialogFormVisible = false
    },
    loadMenus({ action, parentNode, callback }) {
      crudMenu.getMenusTree({ pid: parentNode.id }).then(res => {
        parentNode.children = res.data.map(function(obj) {
          if (!obj.leaf) {
            obj.children = null
          }
          return obj
        })
        setTimeout(() => {
          callback()
        }, 100)
      })
    },
    getSupDepts(id) {
      crudMenu.getMenus({ id: id }).then(res => {
        const children = res.data.map(function(obj) {
          if (!obj.leaf && !obj.children) {
            obj.children = null
          }
          return obj
        })
        this.menus = [{ id: 0, label: this.$t('topmenu'), children: children }]
      })
    },
    // 选中图标
    selected(name) {
      this.$set(this.form, 'icon', name)
    },
    imgUrlFormatter(url) {
      if (url === '' || url == null || url === undefined) return
      // 当图片路径相同时,即使源图片更改了,img内显示的也不会去刷新,需要在后面加radom或者当前时间去解决
      return this.baseApi + '/' + url + '?t=' + new Date()
    },
    ImgRemove() {
      this.$refs.upload.clearFiles()
      this.imageUrl = ''
      this.form.bgImagePath = ''
    },
    uploadSuccess(file) {
      this.form.bgImagePath = file.data
    },
    beforeUpload(file) {
      var isJPG = false
      for (const i in this.fileTypeList) {
        if (file.raw.type.toUpperCase().indexOf(this.fileTypeList[i]) > 0) { isJPG = true }
      }
      const isLt2M = file.raw.size / 1024 / 1024 < 5
      if (!isJPG) {
        // this.showMessage('add', 'error', '上传图片只能是 JPG/PNG/GIF 格式!')
        return false
      }
      if (!isLt2M) {
        // this.showMessage('add', 'error', '上传图片大小不能超过 2MB!')
        return false
      }
      const url = URL.createObjectURL(file.raw)
      this.imageUrl = url
      return true
    }
  }
}
</script>
<style lang="scss" scoped>

.el-form{
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
  .el-form-item{
    width: 50%;
  }
}

</style>
